package com.app.xinfadi.ui.user;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.app.xinfadi.R;
import com.app.xinfadi.base.BaseActivity;
import com.app.xinfadi.dao_bean.UserLoginBean;
import com.app.xinfadi.dao.UserDao;
import com.app.xinfadi.ui.MainActivity;
import com.app.xinfadi.util.LogUtil;
import com.app.xinfadi.util.SharedPreferencesUtil;
import com.app.xinfadi.util.Toast;


/**
 * 登陆
 *
 * @author WuTengFei
 * @date 2014-11-30 下午2:59:17 <br/>
 */
public class UserLogInActivity extends BaseActivity {
    private static String TAG = "UserLogInActivity";

    private TextView login_reg_new;
    private TextView login_forget_pwd;
    private TextView et_mobile;
    private TextView et_password;
    private Button login_submit;
    private String text_user_name;
    private String text_password;
    private Button test;
    private int witch_page;
    private String current_role = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_login);
        initBundle();
        initView();
        initData();
    }

    private void initBundle() {
        witch_page = getIntent().getIntExtra("witch_page", -1);
        LogUtil.d(TAG, "witch_page:" + witch_page);
    }


    protected void initView() {
        login_reg_new = (TextView) findViewById(R.id.login_reg_new);
        login_forget_pwd = (TextView) findViewById(R.id.login_forget_pwd);
        // 手机号码
        et_mobile = (TextView) findViewById(R.id.inpunt_account);
        et_password = (TextView) findViewById(R.id.inpunt_pwd);
        login_submit = (Button) findViewById(R.id.login_submit);
        test = (Button) findViewById(R.id.test);
        login_reg_new.setOnClickListener(this);
        login_forget_pwd.setOnClickListener(this);
        login_submit.setOnClickListener(this);
        test.setOnClickListener(this);
    }

    private void initData() {
        et_mobile.setText(SharedPreferencesUtil.getInstance().getUserLoginName());
    }



    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent = new Intent();
        switch (v.getId()) {
//            case R.id.login_reg_new:
//                intent.setClass(this, UserRegistActivity.class);
//                startActivity(intent);
//                break;
            case R.id.login_forget_pwd:
                intent.setClass(this, UserFindPwdActivity.class);
                startActivity(intent);
                break;
            // 测试,直接跳过登录界面
            case R.id.test:
//                LoginSuccess();
                break;
            case R.id.login_submit:
                text_user_name = et_mobile.getText().toString().trim();
                text_password = et_password.getText().toString().trim();
                StringBuffer errorBuffer = new StringBuffer();
                boolean canSave = true;
                if (text_user_name.equals("")) {
                    errorBuffer.append("账号");
                    canSave = false;
                }
                if (text_password.equals("")) {
                    errorBuffer.append("密码");
                    canSave = false;
                }
                if (!canSave) {
                    errorBuffer.append(" 不能为空！");
                    Toast.makeText(context, errorBuffer.toString(), Toast.LENGTH_SHORT).show();
                } else {
                    login();
                }

                break;
        }

    }

    /**
     * 登陆
     */
    private void login() {
        LogUtil.e(TAG, "login");
        showProgressDialog("正在登陆");
        UserDao userDao = new UserDao();
        userDao.login(text_user_name, text_password, new Response.Listener<UserLoginBean>() {

            @Override
            public void onResponse(UserLoginBean userLoginBean) {
                if (userLoginBean.success) {
                    SharedPreferencesUtil.getInstance().saveUserInfo(userLoginBean.user.user_id,text_user_name,userLoginBean.user.user_role,userLoginBean.user.phone );
                    LoginSuccess();
                } else {
                    Toast.makeText(context, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                }
                dismissProgressDialog();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
//                SharedPreferencesUtil.getInstance().saveUserInfo(text_user_name);
//                LoginSuccess(current_role);
                dismissProgressDialog();

            }
        });
//        }
    }


    /**
     * 在用户登录成功后,保存用户信息,跳转界面
     */
    private void LoginSuccess() {
//        setAlias(text_user_name);
        Toast.makeText(context, "登陆成功", Toast.LENGTH_SHORT).show();
        closeSoftKeyBoard(this);
//        popAllActivityExceptOne(MainActivity.class);
        Intent intent = new Intent(context, MainActivity.class);
        startActivity(intent);
        finish();
    }
    //    @SuppressLint("HandlerLeak")
//    private final Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(android.os.Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case MSG_SET_ALIAS:
//                    Log.d(TAG, "Set alias in handler.");
//                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
//                    break;
//
//                case MSG_SET_TAGS:
//                    Log.d(TAG, "Set tags in handler.");
//                    JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
//                    break;
//
//                default:
//                    Log.i(TAG, "Unhandled msg - " + msg.what);
//            }
//        }
//    };
//    private MyHandler mHandler = new MyHandler(this);
//    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
//
//        @Override
//        public void gotResult(int code, String alias, Set<String> tags) {
//            String logs;
//            switch (code) {
//                case 0:
//                    logs = "Set tag and alias success";
//                    Log.i(TAG, logs);
//                    break;
//
//                case 6002:
//                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
//                    Log.i(TAG, logs);
//                    if (JPushUtil.isConnected(getApplicationContext())) {
//                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
//                    } else {
//                        Log.i(TAG, "No network");
//                    }
//                    break;
//
//                default:
//                    logs = "Failed with errorCode = " + code;
//                    Log.e(TAG, logs);
//            }
//
//            // JPushUtil.showToast(logs, getApplicationContext());
//        }
//
//    };
//    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {
//
//        @Override
//        public void gotResult(int code, String alias, Set<String> tags) {
//            String logs;
//            switch (code) {
//                case 0:
//                    logs = "Set tag and alias success";
//                    Log.i(TAG, logs);
//                    break;
//
//                case 6002:
//                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
//                    Log.i(TAG, logs);
//                    if (JPushUtil.isConnected(getApplicationContext())) {
//                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
//                    } else {
//                        Log.i(TAG, "No network");
//                    }
//                    break;
//
//                default:
//                    logs = "Failed with errorCode = " + code;
//                    Log.e(TAG, logs);
//            }
//
//            // JPushUtil.showToast(logs, getApplicationContext());
//        }
//
//    };


    /**
     * 设置 JPush alias
     *
     * @param alias
     */
    private void setAlias(String alias) {
        // 调用JPush API设置Alias
//        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

//    static class MyHandler extends Handler {
//        private final WeakReference<UserLogInActivity> outerClass;
//
//        MyHandler(UserLogInActivity theClass) {
//            outerClass = new WeakReference<UserLogInActivity>(theClass);
//        }
//
//        @Override
//        public void handleMessage(android.os.Message msg) {
//            UserLogInActivity theClass = outerClass.get();
//            switch (msg.what) {
//                case MSG_SET_ALIAS:
//                    Log.d(TAG, "Set alias in handler.");
//                    JPushInterface.setAliasAndTags(theClass.getApplicationContext(), (String) msg.obj, null, theClass.mAliasCallback);
//                    break;
//
//                case MSG_SET_TAGS:
//                    Log.d(TAG, "Set tags in handler.");
//                    JPushInterface.setAliasAndTags(theClass.getApplicationContext(), null, (Set<String>) msg.obj, theClass.mTagsCallback);
//                    break;
//
//                default:
//                    Log.i(TAG, "Unhandled msg - " + msg.what);
//            }
//        }
//    }
}
